'use strict';
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as fs from 'fs';

let log = vscode.window.createOutputChannel("smartC/log");
log.show();

function isDataFileExist(){
    log.appendLine("data file path:"+__dirname);
    fs.open(__dirname + '/test.txt', 'r', (err, fd) => {
        if(err){
            log.appendLine('data file does not exist.');
            return false;
        }else{
            return true;
        }
    });
}

function initDataFile(){
    fs.writeFile(__dirname + '/test.txt', new Buffer('hahahahahaEEEEaaaa'), {flag: 'a'}, (err) => {
        if(err) {
            log.appendLine('data file init err.');
        } else {
            log.appendLine('data file init ok.');
        }
    });
    return 0;
}

function loadDataFile(){
    fs.readFile(__dirname + '/test.txt', {flag: 'r+', encoding: 'utf8'}, (err, data) => {
        if(err){
            log.appendLine('load data file err.');
        } else{
            log.appendLine('data file:' + data.toString());
        }
    });
    return 0;
}

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

    if(!isDataFileExist()){
        log.appendLine('1');
        initDataFile();
        log.appendLine('2');
    }
    log.appendLine('3');
    loadDataFile();
    log.appendLine('4');

    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "helloExt" is now active!');

    //=========================== hello 命令行 ===========================
    // The command has been defined in the package.json file
    // Now provide the implementation of the command with  registerCommand
    // The commandId parameter must match the command field in package.json
    let disposable = vscode.commands.registerCommand('extension.sayHello', () => {
        // The code you place here will be executed every time your command is executed

        // Display a message box to the user
        vscode.window.showInformationMessage('Hello World!');
    });
    context.subscriptions.push(disposable);

    //=========================== catcoding 命令行 ===========================
    let currentPanel: vscode.WebviewPanel | undefined = undefined;

    context.subscriptions.push(vscode.commands.registerCommand('catCoding.start', () => {
        //const columnToShowIn = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined;
        if (currentPanel) {
            // If we already have a panel, show it in the target column
            //vscode.window.showInformationMessage('===CRY_DEBUG===:' + columnToShowIn);
            currentPanel.reveal(vscode.ViewColumn.Two);
        } else {
            // Otherwise, create a new panel
            // Create and show a new webview
            const panel = vscode.window.createWebviewPanel(
                'catCoding', // Identifies the type of the webview. Used internally
                "Cat Coding", // Title of the panel displayed to the user
                vscode.ViewColumn.Two, // Editor column to show the new webview panel in.
                {
                    enableScripts: true
                } // Webview options. More on these later.
            );
            currentPanel = panel;

            panel.title = 'SmartC';
            panel.webview.html = getWebviewContent();

            // Reset when the current panel is closed
            panel.onDidDispose(() => {
                // When the panel is closed, cancel any future updates to the webview content
                currentPanel = undefined;
            }, null, context.subscriptions);

        }
    }));

    context.subscriptions.push(vscode.window.onDidChangeTextEditorSelection(e => sendFileName(currentPanel, e)));

}

function getWebviewContent() {
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Coding</title>
</head>
<body>
    <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
    <h1 id="lines-of-code-counter">0</h1>
    <p id="show-txt"></p>
    <script>
        const counter = document.getElementById('lines-of-code-counter');

        let count = 0;
        setInterval(() => {
            counter.textContent = count++;
        }, 100);
        // Handle the message inside the webview
        window.addEventListener('message', event => {
            const message = event.data; // The JSON data our extension sent
            if (message.text) {
                const showTxt = document.getElementById('show-txt');
                showTxt.textContent = message.text;
            }
        });
    </script> 
</body>
</html>`;
}

function sendFileName(panel: vscode.WebviewPanel | undefined, e : vscode.TextEditorSelectionChangeEvent){
    let editor = vscode.window.activeTextEditor;
    if (!editor) {
        log.appendLine('===ERR===: Editor not found!');
        return;
    }
    let doc = editor.document;
    let docName = doc.fileName;  //获取文件名
    let pattern = /(\.c$)|(\.cpp$)|(\.h$)/g;
    let m: RegExpExecArray | null;
    if (!(m = pattern.exec(docName))){
        return;
    }

    let docContent = doc.getText();  //获取文件文本
    let startOffset = e.textEditor.document.offsetAt(e.selections[0].start);
    let endOffset = e.textEditor.document.offsetAt(e.selections[0].end);
    let selectedStr = docContent.substr(startOffset, endOffset - startOffset);

    if (selectedStr.length < 1){
        return;
    }

    log.appendLine('===selectedStr===:' + selectedStr);

    if(panel){
        panel.webview.postMessage({ text: selectedStr });
    }
}

// this method is called when your extension is deactivated
export function deactivate() {
}